package com.sbhotel.chotellauncher.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.sbhotel.chotellauncher.constant.Constants;
import com.sbhotel.chotellauncher.entity.LauncherMainMenuBean;

import org.w3c.dom.Text;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.MODE_PRIVATE;

public class LauncherConfigUtil {

    // 向指定的文件中写入指定的数据
    public static void writeFileData(Context conText, String fileName, String content) {
        Log.d(Constants.LOG_TAG, "writeFileData");
        try {
            CreateFile(fileName);
            File file = new File(fileName);
            FileOutputStream fos = new FileOutputStream(file); //conText.openFileOutput(fileName, MODE_PRIVATE);//获得FileOutputStream
            //将要写入的字符串转换为byte数组
            byte[] bytes = content.getBytes();
            fos.write(bytes);//将byte数组写入文件
            fos.close();//关闭文件输出流
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //打开指定文件，读取其数据，返回字符串对象
    public static String readFileData(Context conText, String fileName) {

        String result = "";
        try {
            File file = new File(fileName);
            if (!file.exists()) return "";
            FileInputStream fis = new FileInputStream(file);

            //获取文件长度
            int lenght = fis.available();
            byte[] buffer = new byte[lenght];
            fis.read(buffer);
            //将byte数组转换成指定格式的字符串
            result = new String(buffer, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;

    }

    //如果文件不存在则创建

    public static void CreateFile(String path) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.createNewFile();
        }
    }

    public static void createDownloadTask(Context context, String config) {
        Log.d(Constants.LOG_TAG, "createDownloadTask");
        Gson gson = new Gson();
        ArrayList<String> needDownLoadApps = new ArrayList<>();
        ArrayList<String> downLoadAppsPkgName = new ArrayList<>();
        String pkgName = "";
        LauncherMainMenuBean bean = gson.fromJson(config, LauncherMainMenuBean.class);
        //统计所有需要下载的App
        for (int i = 0; i < bean.getData().getCont_list().size(); i++) {
            pkgName = bean.getData().getCont_list().get(i).getApp_package_name();
            if (!TextUtils.isEmpty(pkgName)) {
                if (!checkApkExist(context, bean.getData().getCont_list().get(i).getApp_package_name())) {
                    String url = bean.getData().getCont_list().get(i).getApp_download_url();
                    if (!TextUtils.isEmpty(url)) {
                        if (!needDownLoadApps.contains(url)) {
                            needDownLoadApps.add(url);
                            Log.d(Constants.LOG_TAG, "needDownLoadApps url = " + url);
                            if (!downLoadAppsPkgName.contains(pkgName)) {
                                downLoadAppsPkgName.add(pkgName);
                                Log.d(Constants.LOG_TAG, "needDownLoadApps pkgName = " + pkgName);
                            }
                        }
                    }
                }
            }
        }
        for (int i = 0; i < bean.getData().getService_list().size(); i++) {
            pkgName = bean.getData().getService_list().get(i).getApp_package_name();
            if (!TextUtils.isEmpty(pkgName)) {
                if (!checkApkExist(context, bean.getData().getService_list().get(i).getApp_package_name())) {
                    String url = bean.getData().getService_list().get(i).getApp_download_url();
                    if (!TextUtils.isEmpty(url)) {
                        if (!needDownLoadApps.contains(url)) {
                            needDownLoadApps.add(url);
                            Log.d(Constants.LOG_TAG, "needDownLoadApps url = " + url);
                            if (!downLoadAppsPkgName.contains(pkgName)) {
                                downLoadAppsPkgName.add(pkgName);
                                Log.d(Constants.LOG_TAG, "needDownLoadApps pkgName = " + pkgName);
                            }
                        }
                    }
                }
            }
        }
        Log.d(Constants.LOG_TAG, "createDownloadTask startService");

        if(needDownLoadApps.size() == 0) {
            context.sendBroadcast(new Intent("com.sbhotel.config.success"));
        } else {
            Intent intent = new Intent();
            intent.setClassName("com.sbhotel.upgrade", "com.sbhotel.upgrade.service.AppDownloadService");
            intent.putStringArrayListExtra("pkgNames", downLoadAppsPkgName);
            intent.putStringArrayListExtra("downloadUrls", needDownLoadApps);
            intent.putExtra("action", "install");
            context.startService(intent);
        }
    }

    public static boolean checkApkExist(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName))
            return false;
        if (packageName == null || packageName.isEmpty()) {
            return false;
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            //e.printStackTrace();
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;//true为安装了，false为未安装
        }
    }

    public static final boolean checkConfigFile(Context context, String configStr) {
        boolean config_ok = false;
        Gson gson = new Gson();
        LauncherMainMenuBean bean = gson.fromJson(configStr, LauncherMainMenuBean.class);

        for (int i = 0; i < bean.getData().getCont_list().size(); i++) {
            String pkgName = bean.getData().getCont_list().get(i).getApp_package_name();
            String url = bean.getData().getCont_list().get(i).getApp_download_url();
            if (!TextUtils.isEmpty(pkgName) && !TextUtils.isEmpty(url)) {
                if (checkApkExist(context, pkgName)) {
                    config_ok = true;
                } else {
                    config_ok = false;
                    Log.d(Constants.LOG_TAG, "getCont_list pkgName = " + pkgName);
                    return config_ok;
                }
            }
        }

        for (int i = 0; i < bean.getData().getService_list().size(); i++) {
            String url = bean.getData().getService_list().get(i).getApp_download_url();
            String pkgName = bean.getData().getService_list().get(i).getApp_package_name();
            if (!TextUtils.isEmpty(pkgName) && !TextUtils.isEmpty(url)) {
                if (checkApkExist(context, pkgName)) {
                    config_ok = true;
                } else {
                    config_ok = false;
                    Log.d(Constants.LOG_TAG, "getService_list pkgName = " + pkgName);
                    return config_ok;
                }
            }
        }
        return config_ok;
    }

}
